<template>
  <div class="flex">
    <!-- 筛选侧边栏 -->
    <div class="w-200px mr-20px">
      <ContentWrap class="!mb-0">
        <div class="mb-10px">
          <el-input v-model="filterText" placeholder="搜索班级" clearable>
            <template #prefix>
              <Icon icon="ep:search" />
            </template>
          </el-input>
        </div>
        <div class="tree-container">
          <el-tree
            ref="treeRef"
            :data="treeData"
            :props="defaultProps"
            :filter-node-method="filterNode"
            :load="loadNode"
            lazy
            node-key="id"
            highlight-current
            check-on-click-node
            accordion
            :default-expanded-keys="defaultExpandedKeys"
            @current-change="handleNodeClick"
          />
        </div>
      </ContentWrap>
    </div>

    <!-- 主内容区 -->
    <div class="flex-1">
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="食物名称" prop="foodName">
            <el-input
              v-model="queryParams.foodName"
              placeholder="请输入食物名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-160px"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              class="!w-120px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"
              ><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button
            >
            <el-button @click="resetQuery"
              ><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button
            >
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['school:recipe-food-allergy:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
            <!-- <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['school:recipe-food-allergy:export']"
            >
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button> -->
            <el-button
              type="danger"
              plain
              :disabled="isEmpty(checkedIds)"
              @click="handleDeleteBatch"
              v-hasPermi="['school:recipe-food-allergy:delete']"
            >
              <Icon icon="ep:delete" class="mr-5px" /> 批量删除
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table
          row-key="id"
          v-loading="loading"
          :data="list"
          :stripe="true"
          :show-overflow-tooltip="true"
          @selection-change="handleRowCheckboxChange"
        >
          <el-table-column type="selection" width="55" />
          <!-- <el-table-column label="编号" align="center" prop="id" /> -->
          <el-table-column label="班级" align="center" prop="className" />
          <el-table-column label="学生" align="center" prop="studentName" />
          <el-table-column label="食物分类" align="center" prop="foodTypeName" />
          <!-- <el-table-column label="食物编号" align="center" prop="foodId" /> -->
          <el-table-column label="食物名称" align="center" prop="foodName" />
          <el-table-column label="过敏程度" align="center" prop="allergyLevel">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.SCHOOL_FOOD_ALLERGY" :value="scope.row.allergyLevel" />
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180px"
          />
          <el-table-column label="操作" align="center" min-width="120px">
            <template #default="scope">
              <!-- <el-button
                link
                type="primary"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['school:recipe-food-allergy:update']"
              >
                编辑
              </el-button> -->
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['school:recipe-food-allergy:delete']"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>

      <!-- 表单弹窗：添加/修改 -->
      <RecipeFoodAllergyForm ref="formRef" @success="getList" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { RecipeFoodAllergyApi, RecipeFoodAllergy } from '@/api/school/recipe/allergy'
import RecipeFoodAllergyForm from './RecipeFoodAllergyForm.vue'
import { ClassesApi } from '@/api/school/classes'
import { StudentApi } from '@/api/school/student'
import { ElTree } from 'element-plus'
import { defaultProps } from '@/utils/tree'
import { useI18n } from 'vue-i18n'
import { useMessage } from '@/hooks/web/useMessage'
import { ref, reactive, onMounted, watch } from 'vue'

/** 食物过敏 列表 */
defineOptions({ name: 'RecipeFoodAllergy' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const list = ref<RecipeFoodAllergy[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  classId: undefined,
  studentId: undefined,
  foodTypeId: undefined,
  foodId: undefined,
  foodName: undefined,
  status: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 筛选相关
const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeData = ref([])
const defaultExpandedKeys = ref([]) // 默认展开的节点key
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await RecipeFoodAllergyApi.getRecipeFoodAllergyPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id, queryParams.classId, queryParams.studentId)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await RecipeFoodAllergyApi.deleteRecipeFoodAllergy(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除食物过敏 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await RecipeFoodAllergyApi.deleteRecipeFoodAllergyList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: RecipeFoodAllergy[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RecipeFoodAllergyApi.exportRecipeFoodAllergy(queryParams)
    download.excel(data, '食物过敏.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 树节点过滤
const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.name.includes(value)
}

// 获取班级树数据
const getClassesTree = async () => {
  try {
    const res = await ClassesApi.getClassesList()
    treeData.value = res

    // 提取二级节点（班级节点）的ID作为默认展开的节点
    const expandedKeys: any = []
    const extractClassIds = (nodes) => {
      if (!nodes || nodes.length === 0) return

      nodes.forEach((node: any) => {
        // 二级节点（班级节点）添加到默认展开列表
        if (node.children && node.children.length > 0) {
          expandedKeys.push(node.id)
        }

        // 递归处理子节点
        if (node.children) {
          extractClassIds(node.children)
        }
      })
    }

    extractClassIds(res)
    defaultExpandedKeys.value = expandedKeys
  } catch (e) {
    console.error('获取班级数据失败:', e)
  }
}

// 懒加载节点
const loadNode = async (node: any, resolve: any) => {
  // 点击班级节点时加载学生列表
  if (node.level === 2) {
    try {
      const res = await StudentApi.getSimpleStudentList(node.data.id)
      const students = res.map((item: any) => {
        // 为学生节点添加唯一标识，避免与班级ID冲突
        return {
          id: `student_${item.id}`, // 添加前缀确保唯一性
          name: item.studentName,
          leaf: true,
          studentId: item.id, // 保存原始学生ID
          type: 'student'
        }
      })
      resolve(students)
    } catch (e) {
      resolve([])
    }
  }
  // 其他层级返回节点的子数据
  else {
    resolve(node?.data?.children || [])
  }
}

// 处理节点点击
const handleNodeClick = (data: any, node: any) => {
  // 清空之前的查询条件
  queryParams.classId = undefined
  queryParams.studentId = undefined

  // 如果是班级节点
  if (node.level === 2) {
    queryParams.classId = data.id
  }
  // 如果是学生节点
  else if (node.level === 3) {
    // 使用原始学生ID而不是带前缀的ID
    queryParams.studentId = data.studentId || data.id
    queryParams.classId = node.parent.data.id
  }
  // 重新查询
  handleQuery()
}

// 监听筛选框变化
watch(filterText, (val) => {
  treeRef.value?.filter(val)
})

/** 初始化 **/
onMounted(() => {
  getList()
  getClassesTree()
})
</script>

<style lang="scss" scoped>
.tree-container {
  height: calc($content-height - 64px);
  overflow-y: auto;
}
</style>
